package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.service.DictService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.XcxUser;
import org.dromara.system.domain.bo.XcxUserBindSysUserBo;
import org.dromara.system.domain.bo.XcxUserBo;
import org.dromara.system.domain.bo.XcxUserUpdateReq;
import org.dromara.system.domain.vo.TalentUserVo;
import org.dromara.system.domain.vo.WechatServiceContentVo;
import org.dromara.system.domain.vo.XcxUserVo;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.mapper.XcxUserMapper;
import org.dromara.system.service.IServiceItemService;
import org.dromara.system.service.ITalentUserService;
import org.dromara.system.service.IXcxUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 小程序用户Service业务层处理
 *
 * @author maoningchuan
 * @date 2025-09-03
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class XcxUserServiceImpl implements IXcxUserService {

    private final XcxUserMapper baseMapper;

    private final SysUserMapper sysUserMapper;

    private final ITalentUserService talentUserService;

    private final DictService dictService;

    private final IServiceItemService serviceItemService;

    /**
     * 查询小程序用户
     *
     * @param xcxUserId 主键
     * @return 小程序用户
     */
    @Override
    public XcxUserVo queryById(Long xcxUserId) {
        return baseMapper.selectVoById(xcxUserId);
    }

    @Override
    public XcxUserVo queryByOpenId(String openId) {
        LambdaQueryWrapper<XcxUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XcxUser::getOpenId, openId);
        return baseMapper.selectVoOne(queryWrapper);
    }

    /**
     * 分页查询小程序用户列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 小程序用户分页列表
     */
    @Override
    public TableDataInfo<XcxUserVo> queryPageList(XcxUserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<XcxUser> lqw = buildQueryWrapper(bo);
        Page<XcxUserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的小程序用户列表
     *
     * @param bo 查询条件
     * @return 小程序用户列表
     */
    @Override
    public List<XcxUserVo> queryList(XcxUserBo bo) {
        LambdaQueryWrapper<XcxUser> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<XcxUser> buildQueryWrapper(XcxUserBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<XcxUser> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(XcxUser::getUserId);
        lqw.eq(bo.getUserId() != null, XcxUser::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getOpenId()), XcxUser::getOpenId, bo.getOpenId());
        lqw.eq(StringUtils.isNotBlank(bo.getAvatarUrl()), XcxUser::getAvatarUrl, bo.getAvatarUrl());
        lqw.like(StringUtils.isNotBlank(bo.getUserName()), XcxUser::getUserName, bo.getUserName());
        lqw.eq(StringUtils.isNotBlank(bo.getIdcardType()), XcxUser::getIdcardType, bo.getIdcardType());
        lqw.eq(StringUtils.isNotBlank(bo.getIdcardNum()), XcxUser::getIdcardNum, bo.getIdcardNum());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), XcxUser::getSex, bo.getSex());
        lqw.eq(bo.getBirthday() != null, XcxUser::getBirthday, bo.getBirthday());
        lqw.eq(StringUtils.isNotBlank(bo.getPhonenumber()), XcxUser::getPhonenumber, bo.getPhonenumber());
        lqw.like(StringUtils.isNotBlank(bo.getWorkCompanyName()), XcxUser::getWorkCompanyName, bo.getWorkCompanyName());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkCompanyType()), XcxUser::getWorkCompanyType, bo.getWorkCompanyType());
        lqw.eq(StringUtils.isNotBlank(bo.getQuxian()), XcxUser::getQuxian, bo.getQuxian());
        lqw.eq(StringUtils.isNotBlank(bo.getXiangzhen()), XcxUser::getXiangzhen, bo.getXiangzhen());
        lqw.eq(StringUtils.isNotBlank(bo.getGraduateFrom()), XcxUser::getGraduateFrom, bo.getGraduateFrom());
        lqw.eq(StringUtils.isNotBlank(bo.getMajor()), XcxUser::getMajor, bo.getMajor());
        lqw.eq(bo.getGraduateDate() != null, XcxUser::getGraduateDate, bo.getGraduateDate());
        lqw.eq(StringUtils.isNotBlank(bo.getLearningForms()), XcxUser::getLearningForms, bo.getLearningForms());
        lqw.eq(StringUtils.isNotBlank(bo.getDegree()), XcxUser::getDegree, bo.getDegree());
        lqw.eq(StringUtils.isNotBlank(bo.getNewFengjieTalentLevel()), XcxUser::getNewFengjieTalentLevel, bo.getNewFengjieTalentLevel());
        lqw.eq(StringUtils.isNotBlank(bo.getMeetChongqingTalentDesc()), XcxUser::getMeetChongqingTalentDesc, bo.getMeetChongqingTalentDesc());
        lqw.eq(StringUtils.isNotBlank(bo.getMeetFengjieTalentDesc()), XcxUser::getMeetFengjieTalentDesc, bo.getMeetFengjieTalentDesc());
        lqw.eq(StringUtils.isNotBlank(bo.getProvePapers()), XcxUser::getProvePapers, bo.getProvePapers());
        lqw.like(StringUtils.isNotBlank(bo.getTalentPaperName()), XcxUser::getTalentPaperName, bo.getTalentPaperName());
        lqw.eq(bo.getTalentPaperDate() != null, XcxUser::getTalentPaperDate, bo.getTalentPaperDate());
        lqw.eq(StringUtils.isNotBlank(bo.getProfessionalSkillLevel()), XcxUser::getProfessionalSkillLevel, bo.getProfessionalSkillLevel());
        lqw.eq(StringUtils.isNotBlank(bo.getSkillTalentType()), XcxUser::getSkillTalentType, bo.getSkillTalentType());
        lqw.eq(StringUtils.isNotBlank(bo.getHangyeType()), XcxUser::getHangyeType, bo.getHangyeType());
        lqw.eq(StringUtils.isNotBlank(bo.getIndustryCategory()), XcxUser::getIndustryCategory, bo.getIndustryCategory());
        lqw.eq(StringUtils.isNotBlank(bo.getJobCategory()), XcxUser::getJobCategory, bo.getJobCategory());
        lqw.like(StringUtils.isNotBlank(bo.getWorkLiaisonName()), XcxUser::getWorkLiaisonName, bo.getWorkLiaisonName());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkLiaisonPhone()), XcxUser::getWorkLiaisonPhone, bo.getWorkLiaisonPhone());
        lqw.like(StringUtils.isNotBlank(bo.getServiceLiaisonName()), XcxUser::getServiceLiaisonName, bo.getServiceLiaisonName());
        lqw.eq(StringUtils.isNotBlank(bo.getServiceLiaisonPhone()), XcxUser::getServiceLiaisonPhone, bo.getServiceLiaisonPhone());
        lqw.like(StringUtils.isNotBlank(bo.getManageWorkName()), XcxUser::getManageWorkName, bo.getManageWorkName());
        lqw.eq(bo.getManageWorkId() != null, XcxUser::getManageWorkId, bo.getManageWorkId());
        lqw.like(StringUtils.isNotBlank(bo.getSubmitWorkName()), XcxUser::getSubmitWorkName, bo.getSubmitWorkName());
        lqw.eq(bo.getSubmitWorkId() != null, XcxUser::getSubmitWorkId, bo.getSubmitWorkId());
        lqw.eq(StringUtils.isNotBlank(bo.getAccreditationCriteria()), XcxUser::getAccreditationCriteria, bo.getAccreditationCriteria());
        lqw.eq(bo.getExpireDate() != null, XcxUser::getExpireDate, bo.getExpireDate());
        return lqw;
    }

    /**
     * 新增小程序用户
     *
     * @param bo 小程序用户
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(XcxUserBo bo) {
        XcxUser add = MapstructUtils.convert(bo, XcxUser.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setUserId(add.getUserId());
        }
        return flag;
    }

    /**
     * 修改小程序用户
     *
     * @param bo 小程序用户
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(XcxUserBo bo) {
        XcxUser update = MapstructUtils.convert(bo, XcxUser.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(XcxUser entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除小程序用户信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public void updateProfile(XcxUserUpdateReq bo, Long userId) {
        XcxUser update = MapstructUtils.convert(bo, XcxUser.class);
        update.setUserId(userId);
        baseMapper.updateById(update);
    }

    @Override
    public Boolean bindSysUser(XcxUserBindSysUserBo xcxUserBindSysUserBo) {
        Long sysUserId = xcxUserBindSysUserBo.getSysUserId();
        SysUser sysUser = sysUserMapper.selectById(sysUserId);
        if (sysUser == null) {
            throw new ServiceException("关联用户不存在");
        }
        XcxUser xcxUser = baseMapper.selectById(xcxUserBindSysUserBo.getUserId());
        xcxUser.setSysUserId(xcxUserBindSysUserBo.getSysUserId());
        return baseMapper.updateById(xcxUser) > 0;
    }

    @Override
    public XcxUserVo getXcxUserInfo(Long xcxUserId) {
        XcxUserVo xcxUserVo = queryById(xcxUserId);
        String phonenumber = xcxUserVo.getPhonenumber();
        if (StringUtils.isNotEmpty(phonenumber)) {
            List<TalentUserVo> talentUserVos = talentUserService.queryByPhoneNumber(phonenumber);
            if (!CollectionUtils.isEmpty(talentUserVos)) {
                TalentUserVo talentUserVo = talentUserVos.get(0);
                String newFengjieTalentLevelName = dictService.getDictLabel("new_fengjie_talent_level", talentUserVo.getNewFengjieTalentLevel());
                xcxUserVo.setNewFengjieTalentLevelDesc(newFengjieTalentLevelName);
            }
        }
        return xcxUserVo;
    }

    @Override
    public List<WechatServiceContentVo> getAvailableServiceContent(Long xcxUserId) {
        XcxUserVo xcxUserVo = queryById(xcxUserId);
        String phonenumber = xcxUserVo.getPhonenumber();
        if (StringUtils.isNotEmpty(phonenumber)) {
            List<TalentUserVo> talentUserVos = talentUserService.queryByPhoneNumber(phonenumber);
            if (!CollectionUtils.isEmpty(talentUserVos)) {
                TalentUserVo talentUserVo = talentUserVos.get(0);
                String newFengjieTalentLevel = talentUserVo.getNewFengjieTalentLevel();
                return serviceItemService.findServiceItemContentByTalentLevel(newFengjieTalentLevel);
            }
        }
        return List.of();
    }
}
